import React, { useEffect, useState } from 'react'
import {
  IEmployee,
  IProjectToEmployeeLink,
} from '../../starter/model/interfaces'
import style from './mainView.module.scss'
import ProjectColumn from '../../base/components/ProjectColumn/ProjectColumn'
import {  useGetEmployeesQuery } from '../../starter/api/employeesApi'
import { useGetProjectsQuery } from '../../starter/api/projectsApi'
import {
  useCreateProjectEmployeeLinksMutation, useDeleteProjectEmployeeLinkMutation,
  useGetProjectEmployeeLinksQuery, useUpdateProjectEmployeeLinksMutation
} from '../../starter/api/projectEmployeeLinksApi'
import { useDrop } from 'react-dnd'
import CreatePeriod from '../../base/components/CreatePeriod/CreatePeriod'
import { Button, ButtonProps, List, Modal } from 'antd'
import { useActions } from '../../starter/hooks/actions'
import { useAppSelector } from '../../starter/hooks/redux'
import { store } from '../../starter/redux/store'
import { useCreateProjectManagerMutation, useGetProjectManagersQuery } from '../../starter/api/projectManagersApi'
import dayjs from 'dayjs'
export type TMainView = {

}
export default function MainView({}: TMainView) {
  const [isAllLoad, setIsAllLoad] = useState<boolean>(false)
  const {
    setTmpPeriod,
    setModalData,
    onShowModal,

  } = useActions()

  const modalData = useAppSelector(state => state.modal)
  const { data: employees, isSuccess: isSuccessEmployees} = useGetEmployeesQuery()
  const { data: projects, isSuccess: isSuccessProjects} = useGetProjectsQuery()
  const { data: managers, isSuccess: isSuccessManager} = useGetProjectManagersQuery()
  const { data: projectEmployeeLinks, isSuccess: isSuccessProjectEmployeeLinks} = useGetProjectEmployeeLinksQuery({})
  const [createLink, {isLoading: isLoadingCreateLink, isSuccess: isSuccessCreateLink, isError: isErrorCreateLink}] = useCreateProjectEmployeeLinksMutation()
  const [updateLink, {isLoading: isLoadingUpdateLink, isSuccess: isSuccessUpdateLink, isError: isErrorUpdateLink}] = useUpdateProjectEmployeeLinksMutation()


  useEffect(() => {
    setIsAllLoad(isSuccessEmployees && isSuccessProjects && isSuccessProjectEmployeeLinks && isSuccessManager)
  }, [isSuccessEmployees, isSuccessProjects, isSuccessProjectEmployeeLinks, isSuccessManager])

  useEffect(() => {

  }, [isErrorCreateLink, isErrorUpdateLink])

  useEffect(() => {
    if (isSuccessCreateLink || isSuccessUpdateLink) {
      onShowModal(false)
    }
  }, [isSuccessCreateLink, isSuccessUpdateLink])

  useEffect(() => {
    const _buttonSet = modalData.buttonSet.map(button => ({
      ...button,
      loading: isLoadingCreateLink || isLoadingUpdateLink
    }))

    setModalData({
      buttonSet: _buttonSet,
      footer: _buttonSet.map((item, index) => <Button key={index} {...item}/>)
    })
  }, [isLoadingCreateLink, isLoadingUpdateLink])

  const modalDropToProjectHandler = (linkItem: IProjectToEmployeeLink): void => {
    const link = projectEmployeeLinks && projectEmployeeLinks.find(item => item.employee._id === linkItem.employee._id && item.project._id === linkItem.project._id)
    onShowModal(true)
    const buttonSet : ButtonProps[] = [
      {
        type: 'primary',
        onClick: () => addLink(link || linkItem),
        children: 'Ok'
      },
      {
        onClick: () => onShowModal(false),
        children: 'Cancel'
      }
    ]
    setModalData({
      title: 'установите период привлечения сотрудника',
      content: <CreatePeriod onChange={setTmpPeriod} periods={link ? link.periods : []} showRange={true}/>,
      buttonSet,
      footer: buttonSet.map((item, index) => <Button key={index} {...item}/>)
    })
  }

  const addLink = (linkItem: IProjectToEmployeeLink) => {
    const {period: tmpPeriod, doRemovePeriods} = {...store.getState()?.tmp}
    if (tmpPeriod) {
      const _linkItem: IProjectToEmployeeLink = {
        ...linkItem,
        periods: [...linkItem.periods.filter(p => !doRemovePeriods.map(t => t.id).includes(p.id)), tmpPeriod]
      }
      if (!linkItem._id) {
        createLink(_linkItem)
      } else {
        updateLink(_linkItem)
      }
    }
    setTmpPeriod(null)
  }

  const [monitor, projectRef] = useDrop({
    accept: 'project',
    drop(item: IProjectToEmployeeLink | IEmployee) {
      console.log('положили проект на поле')
    },
    collect: monitor => {
      return monitor
    }
  })

  return (
    <>
      {
        !isAllLoad && <div>загрузка...</div>
      }
      {
        isAllLoad &&
        <div className={style.mainWrapper}>
          <Modal title={modalData.title}
                 open={modalData.isShow}
                 footer={modalData.footer}
                 onCancel={() => onShowModal(false)}

          >
            {modalData.content}
          </Modal>
          <div
            ref={projectRef}
            className={style.projectList}>
            {
              projects && projects.map(project => {
                const filteredLinks: IProjectToEmployeeLink[] = projectEmployeeLinks ?
                  projectEmployeeLinks
                    .filter(pe => pe.project._id === project._id && pe.periods
                      .find(p => dayjs(p.startTime) <= dayjs() && dayjs() <= dayjs(p.endTime))) :
                  []
                return (
                  <ProjectColumn
                    key={project._id}
                    project={project}
                    ProjectToEmployeeLinks= {filteredLinks || []}
                    setLink={modalDropToProjectHandler}
                  />
                )
              })
            }
          </div>
        </div>
      }
    </>
  )
}
